/**
 * 
 */
package br.edu.ufcg.embedded.mysocial;

import java.util.ArrayList;
import java.util.Hashtable;
//import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;

import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph;

import br.embedded.socialapp.business.Usuario;

/**
 * @author daniel
 *
 */
public class UserGenerator
{
	public static List<Usuario> generateUsers(int count)
	{
		List<Usuario> usersList = new ArrayList<Usuario>();
		
		for (int i = 1; i <= count; i++)
		{
			Usuario usuario = new Usuario();
			usuario.setLogin("user"+i);
			//usuario.setPasswd("123456");
			//usuario.setFirstName("User"+i);
			//usuario.setLastName("MySocial"+i);
			usersList.add(usuario);
		}
		
		return usersList;
	}
	
	public static int getUser(List<Usuario> users)
	{
		Random random = new Random();
		return random.nextInt(users.size());
	}
	
	public static SimpleWeightedGraph<Usuario, DefaultEdge> buildFriendshipGraph(List<Usuario> usersList, int friendsCount)
	{
		Hashtable<String, Integer> friendsHash = new Hashtable<String, Integer>();
		
		SimpleWeightedGraph<Usuario, DefaultEdge> graph = new SimpleWeightedGraph<Usuario, DefaultEdge>(DefaultEdge.class);
		
		for (Usuario u : usersList) {
			graph.addVertex(u);
			friendsHash.put(u.getLogin(), 0);
		}
		
		while (usersList.size() > 0)
		{
			int index = getUser(usersList);//usersList.size() -1;
			Usuario u1 = usersList.get(index);
			usersList.remove(index);
			
			String l1 = u1.getLogin();
			
			List<Usuario> removeList = new ArrayList<Usuario>();
			
			for (int j = 0; j < usersList.size(); j++)
			{
				Usuario friend = usersList.get(j);
				String l2 = friend.getLogin();
				
				if (friendsHash.get(l1) < friendsCount && friendsHash.get(l2) < friendsCount)
				{
					//if (!(friendsHash.get(l1).contains(l2) || friendsHash.get(l2).contains(l1)))
					//{
						graph.addEdge(u1, friend);
						//friendsHash.get(l1).add(l2);
						//friendsHash.get(l2).add(l1);
						int total1 = friendsHash.get(l1) + 1;
						int total2 = friendsHash.get(l2) + 1;
						friendsHash.put(l1, total1);//new Integer(total1));
						friendsHash.put(l2, total2);// new Integer(total2));
					//}
				}
				
				if (friendsHash.get(l2) == friendsCount)
				{
				   removeList.add(friend);
				}
				if (friendsHash.get(l1) == friendsCount)
					break;
			}
			
			if (removeList.size() > 0)
			{
				for (Usuario f : removeList) {
					usersList.remove(f);
				}
			}
		}
		
		friendsHash = null;
		usersList = null;
		
		return graph;
	}
}
